package com.lzy.sso.client.process;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzy.sso.client.property.SSOClientProperties;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: lzy
 * @Date: 2022/4/30 19:21
 * @Description:
 */
public abstract class AbstractProcessService implements ProcessHandler {
    @Autowired
    protected SSOClientProperties properties;

    /**
     * 处理token 子类实现模板方法
     * @param request
     * @param response
     * @param token
     */
    @Override
    public void process(HttpServletRequest request, HttpServletResponse response, String token) throws Exception {
        HttpClient httpClient= HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(properties.getCasUrl()+"/auth?token="+token);

        HttpResponse execute = httpClient.execute(httpPost);
        String result= EntityUtils.toString(execute.getEntity());

        if(execute.getStatusLine().getStatusCode()==200) {
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(result, Map.class);
            processResult(request,response,map);
        }
    }

    /**
     * 处理置换的信息 模板方法
     * @param request
     * @param response
     * @param map
     */
    protected abstract void processResult(HttpServletRequest request, HttpServletResponse response, Map map);
}
